package com.bulletelc.apollopre.module.web;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.WxShareBean;
import com.bulletelc.apollopre.eventbus.CutPriceProtocolEventBus;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.main.center.intention.IntentionActivity;
import com.bulletelc.apollopre.utils.ImageUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.utils.URLImageParser;
import com.bulletelc.apollopre.widget.FoolBar;
import com.bulletelc.apollopre.widget.ProgressWebView;
import com.bulletelc.apollopre.widget.ShareDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.tauth.Tencent;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by CX on 2018/4/12.
 * 用于加载纯HTML内容
 */

public class WebPageActivity extends MVPBaseActivity<WebPageContract.View, WebPagePresenter> implements WebPageContract.View,
        View.OnClickListener, FoolBar.ClickCallback {

    // views
    private FoolBar flBar;
    private ProgressWebView wvContent;
    private TextView tvContent;
    private ProgressBar pbLoad;
    private Button btnDesign, btnAgree, btnNotAgree;
    private LinearLayout llBargain;
    private WxShareBean wxShareBean;
    private Dialog chooseDialog;
    private LinearLayout llContent;
    public static ShareDialog shareDialog; // 自定义分享的Dialog

    // data
    private Tencent mTencent; // QQ
    private Bitmap weChatBip; // 微信分享的图片Bitmap
    private String url;
    private String orderId;

    @Override
    public int getLayoutRes() {
        return R.layout.webpage_activity;
    }

    @Override
    public void assignViews() {
        flBar = findViewById(R.id.flBar);
        wvContent = findViewById(R.id.wvContent);
        tvContent = findViewById(R.id.tvContent);
        btnDesign = findViewById(R.id.btnDesign);
        btnAgree = findViewById(R.id.btnAgree);
        btnNotAgree = findViewById(R.id.btnNotAgree);
        pbLoad = findViewById(R.id.pbLoad);
        llBargain = findViewById(R.id.llBargain);
        llContent = findViewById(R.id.llContent);
        shareDialog = new ShareDialog(this, mTencent);
    }

    @Override
    public void setListener() {
        flBar.setClickCallback(this);
        btnDesign.setOnClickListener(this);
        btnAgree.setOnClickListener(this);
        btnNotAgree.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (null != intent) {
            int type = intent.getIntExtra(IntentCode.EXTRA_WEB_PAGE_FLAG, 0);
            switch (type) {
                case 2:
                    showIntentionCase(intent);
                    break;
                case 4:
                    showProtocol(intent);
                    break;
                case 6:
                    showCutPrice(intent);
                    break;
                case 8:
                    showCutPriceExplain(intent);
                    break;
                default:

                    break;
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && wvContent.canGoBack()) {
            wvContent.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSuccessAgreement(String content) {
        if (!"".equals(content)) {
            tvContent.setText(Html.fromHtml(content, new URLImageParser(tvContent, this), null));
        }
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorAgreement(String error) {
        ToastUtil.showShortToast(this, error);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onFailAgreement(String fail) {
        ToastUtil.showShortToast(this, fail);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onSuccessBargain(WxShareBean wxShareBean) {
        if (null != wxShareBean) {
            flBar.setDrawableRight(this.getResources().getDrawable(R.drawable.sel_share));
            this.wxShareBean = wxShareBean;
            initWebView();

            wvContent.loadUrl(wxShareBean.getUrl());
            tvContent.setVisibility(View.GONE);
            wvContent.setVisibility(View.VISIBLE);
            llBargain.setVisibility(View.GONE);

            // 开启事件，改变OrderDetailActivity数据
            CutPriceProtocolEventBus eventBus = new CutPriceProtocolEventBus();
            eventBus.setCode(GlobalConfig.CUT_PRICE_COMFIRM);
            EventBus.getDefault().post(eventBus);
        }
    }

    @Override
    public void onErrorBargain(String error) {
        ToastUtil.showShortToast(this, error);
    }

    @Override
    public void onFailBargain(String fail) {
        ToastUtil.showShortToast(this, fail);
    }

    @Override
    protected WebPagePresenter createPresenter() {
        return new WebPagePresenter();
    }

    /**
     * 初始化WebView
     */
    private void initWebView() {
        WebSettings settings = wvContent.getSettings();

        //支持插件
        settings.setJavaScriptEnabled(true);//支持js
        settings.setDomStorageEnabled(true);

        //缩放操作
        settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为False，则该WebView不可缩放
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        settings.setSupportZoom(true); //支持缩放，默认为True。是下面那个的前提。

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不缓存
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        //设置自适应屏幕，两者合用
        settings.setUseWideViewPort(true); //将图片调整到适合WebView的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        wvContent.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                showGuideMask();
                return true;
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnDesign:
                Intent intentIntention = new Intent(this, IntentionActivity.class);
                startActivity(intentIntention);
                finish();
                break;
            case R.id.btnAgree:
                presenter.getBargain(orderId);
                break;
            case R.id.btnNotAgree:
                finish();
                break;
        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
        showShareDialog();
    }

    /**
     * 分享内容
     */
    public void showShareDialog() {
        String url = NetWorkPath.HOST_PATH + "activity/bargain?id=" + MyUtil.getUrlValueByName(wxShareBean.getUrl(), "id");
        shareDialog.setWxShareBean(url, wxShareBean.getTitle(), wxShareBean.getDesc(), wxShareBean.getIcon());
        // 获取微信分享的图片
        Glide.with(this).load(wxShareBean.getIcon()).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) resource;
                weChatBip = bitmapDrawable.getBitmap();
                shareDialog.setBitmap(ImageUtil.compressByScale(weChatBip, 120, 120, false));
            }
        });

        shareDialog.showShareDialog();

    }

    /**
     * 显示砍价分享引导Dialog
     */
    public void showGuideMask() {
        if (chooseDialog == null) {
            View v = LayoutInflater.from(this).inflate(R.layout.guide_mask_layout, null);
            chooseDialog = new Dialog(this, R.style.mask_dialog);
            chooseDialog.setContentView(v);

            Window window = chooseDialog.getWindow();
            window.getDecorView().setPadding(0, 120, 0, 0);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.TOP;
            window.setAttributes(params);

            chooseDialog.show();
        } else {
            chooseDialog.show();
        }
    }

    /**
     * 进入砍价
     *
     * @param intent
     */
    private void showCutPrice(Intent intent) {
        flBar.setTitle("砍价免费拿");
        MyUtil.setProgressBar(pbLoad, true);
        orderId = intent.getStringExtra(IntentCode.EXTRA_KEY_ORDER_ID);
        if (intent.getIntExtra(IntentCode.EXTRA_CUT_PRICE_GROUP, 0) == 0) {
            // 没有砍价
            url = intent.getStringExtra(IntentCode.EXTRA_KEY_URL);
            tvContent.setVisibility(View.VISIBLE);
            presenter.getAgreement(url);
            llBargain.setVisibility(View.VISIBLE);
        } else {
            // 已经砍价
            presenter.getBargain(orderId);
        }
    }

    /**
     * 砍价活动说明
     *
     * @param intent
     */
    private void showCutPriceExplain(Intent intent) {
        flBar.setTitle("活动说明");
        wvContent.setVisibility(View.VISIBLE);
        url = intent.getStringExtra(IntentCode.EXTRA_KEY_URL);
        initWebView();
        wvContent.loadUrl(url);
    }

    /**
     * 条款协议Html
     *
     * @param intent
     */
    private void showProtocol(Intent intent) {
        flBar.setTitle("条款协议");
        MyUtil.setProgressBar(pbLoad, true);
        url = intent.getStringExtra(IntentCode.EXTRA_KEY_URL);
        tvContent.setVisibility(View.VISIBLE);
        presenter.getAgreement(url);
    }

    /**
     * 显示案例详情
     *
     * @param intent
     */
    private void showIntentionCase(Intent intent) {
        flBar.setTitle("案例详情");
        wvContent.setVisibility(View.VISIBLE);
        btnDesign.setVisibility(View.VISIBLE);
        url = intent.getStringExtra(IntentCode.EXTRA_KEY_URL);
        initWebView();
        wvContent.loadUrl(url);
    }

}
